package com.atguigu.demojuc.chap05;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author njg
 * @version 1.0
 * @date 2025/6/17 14:36
 *
 */

//countDownLatch 程序计数器
//    案例：6个同学陆续离开教室后值班同学才可以关门。
public class CountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(6);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "开始学习");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() + "\t" + "学习结束离开教室");
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "同学"+i).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t" + "所有同学离开完毕，锁门");
    }
}
